package com.wiscamp.ninechapters.accounts.domain.repositories;

import com.wiscamp.ninechapters.accounts.domain.models.OrderPayment;
import com.wiscamp.ninechapters.accounts.infrastructure.mappers.OrderPaymentMapper;
import com.wiscamp.ninechapters.accounts.infrastructure.po.OrderPaymentPO;
import cube.ddd.aspect.AopDataException;
import com.wiscamp.ninechapters.common.persistence.DbHelper;
import jakarta.validation.constraints.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;

/**
 * Payment Repository
 */
@Repository
public class PaymentsRepository {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private OrderPaymentMapper orderPaymentMapper;

    @Autowired
    public PaymentsRepository(OrderPaymentMapper orderPaymentMapper) {
        this.orderPaymentMapper = orderPaymentMapper;
    }

    //region converter
    public OrderPayment toOrderPayment(@NotNull OrderPaymentPO po) {
        var entity = new OrderPayment();
        BeanUtils.copyProperties(po, entity);
        return entity;
    }

    public OrderPaymentPO toOrderPaymentPO(@NotNull OrderPayment entity) {
        var po = new OrderPaymentPO();
        BeanUtils.copyProperties(entity, po);
        return po;
    }
    //endregion

    @AopDataException
    public OrderPayment createOrderPayment(long userId, String paymentType, String transcationNumber, String goodsCode, double amount) {
        OrderPayment payment = new OrderPayment();
        payment.setPaymentType(paymentType);
        payment.setUserId(userId);
        payment.setAmount(amount);
        payment.setTransactionNumber(transcationNumber);
        payment.setGoodsCode(goodsCode);
        payment.setOrderTime(LocalDateTime.now());

        var po = toOrderPaymentPO(payment);
        var savedPO = DbHelper.save(po, orderPaymentMapper::saveAndFlush);
        return toOrderPayment(savedPO);
    }

    @AopDataException
    public OrderPayment getOrderPayment(String transactionNumber) {
        var po = orderPaymentMapper.getOrderPayment(transactionNumber);
        return toOrderPayment(po);
    }

    @AopDataException
    public OrderPayment getOrderPayment(long orderId) {
        var po = orderPaymentMapper.getOrderPayment(orderId);
        return toOrderPayment(po);
    }

    @AopDataException
    public OrderPayment saveOrderPayment(OrderPayment orderPayment) {
        var po = toOrderPaymentPO(orderPayment);
        var savedPO = orderPaymentMapper.saveAndFlush(po);
        return toOrderPayment(savedPO);
    }
}
